#include <iostream>
#include <sstream>
#include "message.h"

using namespace std;


message::message() {
    rev = -1;
    pos = -1;
    len = -1;
    id = -1;
    data = "";
}

message::message(msgType newType) {
    type = newType;
}

message::message(QByteArray bytes) {
    stringstream is(bytes.data());
    char tmp;
    is >> tmp;

    if (tmp == 'a')
        type = ADD;
    else if (tmp == 'r')
        type = REMOVE;
    else if (tmp == 'h')
        type = HASH;
    else if (tmp == 's')
        type = REQUEST_DOC;
    else if (tmp == 'd')
        type = SEND_DOC;

    if (type == ADD) {
        is >> id >> rev >> pos >> len;
        data = bytes.mid((int)is.tellg()+1, len);
    }
    else if (type == REMOVE) {
        is >> id >> rev >> pos >> len;
    }
    else if (type == HASH) {
        is >> len;
        data = bytes.mid((int)is.tellg()+1, len);
    }
    else if (type == SEND_DOC) {
        is >> id >> rev >> len;
        data = bytes.mid((int)is.tellg()+1, len);
    }
}

QByteArray message::toBytes() {
    QString bytes;

    if (type == ADD) {
        bytes = "a " + QString::number(id) + " "  + QString::number(rev) + " " + QString::number(pos) + " " + QString::number(len) + " " + data + " ";
    }
    else if (type == REMOVE) {
        bytes = "r " + QString::number(id) + " " + QString::number(rev) + " " + QString::number(pos) + " " + QString::number(len) + " ";
    }
    else if (type == HASH) {
        bytes = "h " + QString::number(len) + " " + data + " ";
    }
    else if (type == REQUEST_DOC) {
        bytes = "s ";
    }
    else if (type == SEND_DOC) {
        bytes = "d " + QString::number(id) + " " + QString::number(rev) + " " + QString::number(len) + " " + data + " ";
    }

    return bytes.toAscii();
}
